import time
import urllib
from google.appengine.api import users
from google.appengine.api import taskqueue
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

from greeting import *
from count import *
from analytics_pl import *

class MainPage(webapp.RequestHandler):
    def get(self):
	self.response.out.write(template.render('generator_greeting.html', {}))
	
    def post(self):
	
	is_10 = self.request.POST.get('10', None)
        is_100 = self.request.POST.get('100', None)
	is_1000 = self.request.POST.get('1000', None)
        is_10000 = self.request.POST.get('10000', None)
	
	if is_10:
            num = is_10
        elif is_100:
	    num = is_100 
	elif is_1000:
            num = is_1000
        elif is_10000:
            num = is_10000

        # Add the task to the default queue.
        taskqueue.add(url='/generate', params={'num': num})

        self.redirect('/')

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        import logging
        logging.info('---------- blob key 1: ' + resource)
        resource = str(urllib.unquote(resource))
        logging.info('---------- blob key 2: ' + resource)
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info)

class BlobServeHandler(webapp.RequestHandler):
    def get(self):
        import logging
        blob_key = self.request.get('blobkey')
        logging.info('---------- blob key: ' + blob_key)
        self.redirect('/serve/%s' % blob_key)


def main():
    run_wsgi_app(webapp.WSGIApplication([
        ('/', MainPage),
        ('/generate', Generator),
	('/greetingGenerate', GreetingGenerator),
	('/greetingGenerateTask', GreetingGeneratorTask),
	('/count', Count),
	('/countTask', CountTask),
        ('/pipeline_countAuthor', CountAuthor),
        ('/blobServe', BlobServeHandler),
        ('/serve/([^/]+)?', ServeHandler)
    ]))

if __name__ == '__main__':
    main()

